package com.lsj.config.security.service;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * @Author:lin.sj
 * @Data:2021/7/6 22:57
 * @Desc:
 */
@Component("rbacService")
public class MyRbacService {
    /**
     * 判断某用户是否具有该request资源的访问权限
     */
    public boolean hasPermission(HttpServletRequest request, Authentication authentication){
        boolean permission = false;
        Object principal = authentication.getPrincipal(); //获取认证信息
        if(principal instanceof UserDetails){
            //获取权限集合
            UserDetails userDetails = (UserDetails)principal;
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
            //包装本次请求url为权限标识
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(request.getRequestURI());
            //根据url判断是否拥有相同的权限,SimpleGrantedAuthority重写了equal方法，所以可以直接判断
            permission = authorities.contains(simpleGrantedAuthority);

            //鉴权失败时，再次对用户所拥有的权限信息进行判断，判断用户是否包含admin角色，admin角色可以对后台系统做任意操作
            if(!permission){
                simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_admin");
                permission = authorities.contains(simpleGrantedAuthority);
            }
        }
        return permission;
    }

}
